import * as fs from 'node:fs'
import * as path from 'node:path'
import process from 'node:process'
import pino from 'pino'
import { getProjectRoot } from './util'

// 日志级别定义
export enum LogLevel {
  TRACE = 'trace',
  DEBUG = 'debug',
  INFO = 'info',
  WARN = 'warn',
  ERROR = 'error',
  FATAL = 'fatal',
}

// 模块名称定义
export enum ModuleName {
  MAIN = 'MAIN',
  CONFIG = 'CONFIG',
  LOCK = 'LOCK',
  RFID = 'RFID',
  SCREEN = 'SCREEN',
  SYSTEM = 'SYSTEM',
}

// 日志上下文接口
export interface LogContext {
  module?: ModuleName | string
  operation?: string
  error?: string
  solution?: string
  stack?: string
  timestamp?: string
  [key: string]: any
}

// 错误日志接口
export interface ErrorLogContext extends LogContext {
  error: string
  solution?: string
  stack?: string
  severity?: 'low' | 'medium' | 'high' | 'critical'
}

// 确保日志目录存在
function ensureLogDirectory(): string {
  const projectRoot = getProjectRoot()
  const logDir = path.join(projectRoot, 'logs')

  if (!fs.existsSync(logDir)) {
    try {
      fs.mkdirSync(logDir, { recursive: true })
    }
    catch (error) {
      console.warn('无法创建日志目录:', error)
      // 如果无法在项目目录创建日志目录，尝试在用户主目录创建
      const homeDir = process.env.HOME || process.env.USERPROFILE || '/tmp'
      const fallbackLogDir = path.join(homeDir, '.smart-cabinet', 'logs')
      try {
        fs.mkdirSync(fallbackLogDir, { recursive: true })
        console.warn(`日志目录已创建在备用位置: ${fallbackLogDir}`)
        return fallbackLogDir
      }
      catch (fallbackError) {
        console.warn('无法创建备用日志目录:', fallbackError)
        // 最后的备选方案：使用临时目录
        return '/tmp'
      }
    }
  }
  return logDir
}

// 获取日志文件路径
function getLogFilePath(): string {
  const logDir = ensureLogDirectory()
  const today = new Date().toISOString().split('T')[0]
  return path.join(logDir, `smart-cabinet-${today}.log`)
}

// 创建日志传输配置
function createLogTransports(): any[] {
  const transports = []

  // 控制台输出（开发环境）
  if (process.env.NODE_ENV !== 'production') {
    transports.push({
      target: 'pino-pretty',
      options: {
        colorize: true,
        translateTime: 'HH:MM:ss', // 简化时间格式
        ignore: 'pid,hostname,timestamp,module,operation,severity,stack', // 忽略冗余信息
        messageFormat: '{msg}', // 简化消息格式
        levelFirst: true,
      },
    })
  }

  // 文件输出
  try {
    transports.push({
      target: 'pino/file',
      options: {
        destination: getLogFilePath(),
        mkdir: true,
      },
    })
  }
  catch (error) {
    console.warn('无法配置文件日志输出:', error)
  }

  return transports
}

// 创建基础logger
const baseLogger = pino({
  level: process.env.LOG_LEVEL || 'warn', // 默认只显示警告和错误
  timestamp: pino.stdTimeFunctions.isoTime,
  transport: {
    targets: createLogTransports(),
  },
})

// 增强的Logger类
class EnhancedLogger {
  private logger: pino.Logger

  constructor(logger: pino.Logger) {
    this.logger = logger
  }

  /**
   * 格式化日志上下文 - 精简版
   */
  private formatContext(context?: LogContext): any {
    if (!context)
      return {}

    // const formatted: any = {}

    // if (context.module)
    //   formatted.module = context.module
    // if (context.error)
    //   formatted.error = context.error
    // if (context.solution)
    //   formatted.solution = context.solution

    return context
  }

  /**
   * 记录信息日志
   */
  info(message: string, context?: LogContext): void {
    this.logger.info(this.formatContext(context), message)
  }

  /**
   * 记录警告日志
   */
  warn(message: string, context?: LogContext): void {
    this.logger.warn(this.formatContext(context), message)
  }

  /**
   * 记录错误日志
   */
  error(message: string, context?: ErrorLogContext): void {
    const errorContext = {
      ...this.formatContext(context),
      severity: context?.severity || 'medium',
    }
    this.logger.error(errorContext, message)
  }

  /**
   * 记录致命错误日志
   */
  fatal(message: string, context?: ErrorLogContext): void {
    const fatalContext = {
      ...this.formatContext(context),
      severity: 'critical',
    }
    this.logger.fatal(fatalContext, message)
  }

  /**
   * 记录调试日志
   */
  debug(message: string, context?: LogContext): void {
    this.logger.debug(this.formatContext(context), message)
  }

  /**
   * 记录追踪日志
   */
  trace(message: string, context?: LogContext): void {
    this.logger.trace(this.formatContext(context), message)
  }

  /**
   * 记录模块启动失败日志 - 精简版
   */
  moduleStartFailure(moduleName: ModuleName | string, error: Error, solution?: string): void {
    this.error(`${moduleName}启动失败: ${error.message}`, {
      module: moduleName,
      error: error.message,
      solution: solution || '请检查模块配置和依赖',
    })
  }

  /**
   * 记录连接失败日志 - 精简版
   */
  connectionFailure(moduleName: ModuleName | string, error: string, solution?: string): void {
    this.error(`${moduleName}连接失败: ${error}`, {
      module: moduleName,
      error,
      solution,
    })
  }

  /**
   * 获取原始logger实例
   */
  getRawLogger(): pino.Logger {
    return this.logger
  }
}

// 创建并导出增强的logger实例
const logger = new EnhancedLogger(baseLogger)

export default logger
export { EnhancedLogger }
